package com.quanyan.club.web;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.db.TbClub;
import com.quanyan.club.entity.vo.req.*;
import com.quanyan.club.entity.RespClubMember;
import com.quanyan.club.exception.ClubEnum;
import com.quanyan.club.mapper.TbClubMapper;
import com.quanyan.club.service.ClubMemberSearchBizService;
import com.quanyan.club.service.ClubMemberService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuo.shi on 2016/6/1.
 */
@RestController
@RequestMapping("/api/club/member")
public class ClubMemberController extends  BaseController {

    @Autowired
    private ClubMemberService clubMemberService;

    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private ClubMemberSearchBizService clubMemberSearchBizService;

    @RequestMapping("/sortList")
    public APIResponse sortList(@RequestBody Map map){

        Integer clubId = MapUtils.getInteger(map, "clubId");
        Integer sortBy = MapUtils.getInteger(map, "sortBy");
        Integer pageNo = MapUtils.getInteger(map, "pageNo");
        Integer pageSize = MapUtils.getInteger(map, "pageSize");
        if (clubId == null || sortBy == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        if (pageNo == null) {
            pageNo = 1;
        }else {
            pageNo += 1;
        }
        if (pageSize == null){
            pageSize = 12;
        }
        return APIResponse.returnSuccess(
                clubMemberSearchBizService.sortClubMember(clubId, sortBy, pageNo, pageSize));
    }

    @RequestMapping("/searchList")
    public APIResponse searchList(@RequestBody Map map){
        Integer clubId = MapUtils.getInteger(map, "clubId");
        String nickName = MapUtils.getString(map, "nickName");
        if (clubId == null || StringUtil.isBlankOrNull(nickName)){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        return APIResponse.returnSuccess(
                clubMemberSearchBizService.searchClubMember(clubId, nickName));
    }

    /**
     * 俱乐部管理员列表
     */
    @RequestMapping("/administrator/list")
    public APIResponse<List<RespClubMember>> listClubAdministrator(@RequestBody ReqClubMemberList reqClubMemberList, HttpServletRequest request){
        Integer uid = getUid(request, false);
        return APIResponse.returnSuccess(clubMemberService.listClubAdministors(uid, reqClubMemberList.getClubId()));
    }

    /**
     * 俱乐部所有成员列表
     */
    @RequestMapping(value = "/allmember/list")
    public APIResponse<PageObj<List<RespClubMember>>> listClubMembers(@RequestBody ReqClubMemberList reqClubMemberList, HttpServletRequest request){
        Integer uid = getUid(request, false);
        int clubId = reqClubMemberList.getClubId();
        int pageNo = reqClubMemberList.getPageNo()+1;
        int pageSize = reqClubMemberList.getPageSize();
        int total = clubMemberService.countClubMembers(clubId, reqClubMemberList.getShowAdmin());
        List<RespClubMember> clubMemberList =  clubMemberService.listClubMembers(uid, clubId, false, reqClubMemberList.getShowAdmin(), pageNo, pageSize);
        return APIResponse.returnSuccess(PageObj.create(total, pageNo, pageSize, clubMemberList));
    }

    /**
     * 俱乐部所有成员列表
     */
    @RequestMapping(value = "/teammember/list")
    public APIResponse<PageObj<List<RespClubMember>>> listClubTeamMembers(@RequestBody ReqClubMemberList reqClubMemberList, HttpServletRequest request){
        Integer uid = getUid(request, false);
        int clubId = reqClubMemberList.getClubId();
        int pageNo = reqClubMemberList.getPageNo()+1;
        int pageSize = reqClubMemberList.getPageSize();
        int total = clubMemberService.countClubTeamMembers(clubId);
        List<RespClubMember> clubMemberList =  clubMemberService.listClubTeamMembers(uid, clubId, pageNo, pageSize);
        return APIResponse.returnSuccess(PageObj.create(total, pageNo, pageSize, clubMemberList));
    }

    /**
     * 申请加入俱乐部
     */
    @RequestMapping(value = "/apply/join")
//    public APIResponse<Boolean> applyJoinClub(@RequestBody Map<String, String> map,HttpServletRequest request){
    public APIResponse<Boolean> applyJoinClub(@RequestBody ReqClubJoin reqClubJoin,HttpServletRequest request){
//        if (!map.containsKey("clubId")){
//            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
//        }
        int clubId = reqClubJoin.getClubId();
        Object param = request.getAttribute("uid");
        if (param == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        int uid = Integer.valueOf(param.toString());
        boolean isMember = clubMemberService.isClubMember(uid, clubId);
        if (isMember){
            return APIResponse.returnFail(100, "已经是俱乐部成员，不可再次申请");
        }

        boolean isApplied = clubMemberService.isApplyJoinClub(uid, clubId, null);
        if (isApplied){
            return APIResponse.returnFail(101, "已经申请加入，正在审核中");
        }
        boolean ret = clubMemberService.applyJoinClub(uid, clubId, reqClubJoin.getRemark(),reqClubJoin.getLarkAppId());
        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub != null) {
            int joinType = tbClub.getJoinType();
            if (ret && joinType == 1) {
                return APIResponse.returnFail(102, "申请加入成功，等待审核");
            }
        }
        return APIResponse.returnSuccess(ret);
    }

    /**
     * 加入到俱乐部，两种情况：
     * 1. 俱乐部的管理员同意申请加入俱乐部的用户
     * 2. 被邀请的用户同意加入俱乐部
     */
    @RequestMapping(value = "/agree/join")
    public APIResponse<Boolean> agreeJionClub(@RequestBody ReqAgreeJoinClub reqAgreeJoinClub, HttpServletRequest request){
//        if (!map.containsKey("type") || !map.containsKey("clubId")){
//            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
//        }
//        int type = Integer.valueOf(map.get("type")); //同意加入类型：1 俱乐部管理员同意他人的加入申请， 2 被邀请人同意加入俱乐部
//        int clubId = Integer.valueOf(map.get("clubId"));
        int type = reqAgreeJoinClub.getType();
        int clubId = reqAgreeJoinClub.getClubId();
        int invitedUid = reqAgreeJoinClub.getInvitedUid();
        int larkAppId = reqAgreeJoinClub.getLarkAppId();
//        Integer invitedUid = Integer.valueOf(map.get("invitedUid"));  // 被邀请人用户ID   type==1 时必填
        Integer uid = getUid(request, true);
        Integer joinUid = null; //要加入俱乐部的用户ID
        if (type == 1){ //管理员同意
            joinUid = invitedUid;
        }
        if (type == 2){ //被邀请人同意
            joinUid = uid;
        }
        //如果已经是此俱乐部成员，不能加入
        if (clubMemberService.isClubMember(joinUid, clubId)){
            return APIResponse.returnFail(ClubEnum.CLUB_MEMBER_EXIST);
        }
        try {
            boolean isAgreed = clubMemberService.agreeJoinClub(joinUid, clubId, type, larkAppId);
            return APIResponse.returnSuccess(isAgreed);
        }catch (BizException e){
            return APIResponse.returnFail(e.getMessage());
        }
    }

    /**
     * 用户拒绝加入俱乐部，或者管理员拒绝用户加入申请
     */
    @RequestMapping(value = "/disagree/join")
    public APIResponse disagreeJoinClub(@RequestBody ReqAgreeJoinClub reqAgreeJoinClub, HttpServletRequest request){
//        if (!map.containsKey("type") || !map.containsKey("clubId")){
//            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
//        }
//        int type = Integer.valueOf(map.get("type")); //拒绝加入类型：1 俱乐部管理员拒绝他人的加入申请， 2 被邀请人拒绝加入俱乐部
//        int clubId = Integer.valueOf(map.get("clubId"));
        int type = reqAgreeJoinClub.getType();
        int clubId = reqAgreeJoinClub.getClubId();
        int larkAppId = reqAgreeJoinClub.getLarkAppId();
        Integer refuseUid = null;
        Integer uid = getUid(request, true);
        if (type == 1){
//            refuseUid = Integer.valueOf(map.get("refuseUid"));  // 被拒绝人用户ID   type==1 时必填
            refuseUid = reqAgreeJoinClub.getRefuseUid();
        }
        if (type == 2){
            refuseUid = uid;
        }
        //如果已经是此俱乐部成员，不能拒绝
        if (clubMemberService.isClubMember(refuseUid, clubId)){
            return APIResponse.returnFail(ClubEnum.CLUB_MEMBER_EXIST);
        }
        return APIResponse.returnSuccess(clubMemberService.disagreeJoinClub(type, refuseUid, clubId, larkAppId));
    }

    /**
     * 管理员删除（踢掉）俱乐部成员
     */
    @RequestMapping(value = "/fuckout")
    public APIResponse funckoutClub(@RequestBody ReqAgreeJoinClub reqAgreeJoinClub, HttpServletRequest request){
//        if (!map.containsKey("uid") || !map.containsKey("clubId")){
//            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
//        }
        int currentUid = getUid(request, true);
//        int uid = Integer.valueOf(map.get("uid").toString());
//        int clubId = Integer.valueOf(map.get("clubId").toString());
        int clubId = reqAgreeJoinClub.getClubId();
        int uid = reqAgreeJoinClub.getUid();
        int larkAppId = reqAgreeJoinClub.getLarkAppId();
        return APIResponse.returnSuccess(clubMemberService.fuckoutClub(clubId, uid,currentUid,larkAppId));
    }

    /**
     * 俱乐部管理员邀请用户加入俱乐部
     */
    @RequestMapping(value = "/invite")
    public APIResponse<Boolean> inviteClubMember(@RequestBody Map<String, String> map, HttpServletRequest request){
        if (!map.containsKey("uids") || !map.containsKey("clubId")){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        String uids = map.get("uids");  //用户ID，多个用户id，用英文逗号隔开
        Integer clubId = Integer.valueOf(map.get("clubId"));
        Integer type = MapUtils.getInteger(map, "type");        //邀请类型
        Integer inviteUid = getUid(request, true);              //邀请人id
//        if (!isAuthorize(adminUid, clubId, request)){
//            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
//        }
//        String[] uidList = uids.split(",");
//        for (String _uid : uidList){
//            if (StringUtil.isBlankOrNull(_uid)){
//                continue;
//            }
//            Integer uid = Integer.valueOf(_uid);
//            boolean isApplied = clubMemberService.isApplyJoinClub(uid, clubId, inviteUid);
//            if (isApplied){
//                APIResponse<RespUserInfoBase> response = userServiceFacade.queryUserInfo(uid);
//                if (response != null && response.isRet()) {
//                    RespUserInfoBase userInfoBase = response.getData();
//                    return APIResponse.returnFail(userInfoBase.getNickName() + "已经邀请加入了！");
//                }
//            }
//        }
        if(!clubMemberService.isClubAdminMember(inviteUid, clubId))
        {
            return APIResponse.returnFail("请先加入俱乐部并努力获取管理员权限。");
        }
        boolean ret = clubMemberService.inviteClubMember(uids, inviteUid, clubId, type);
        return APIResponse.returnSuccess(ret);
    }

    /**
     * 退出俱乐部
     */
    @RequestMapping(value = "/quit")
    public APIResponse<Boolean> quitClub(@RequestBody ReqAgreeJoinClub reqAgreeJoinClub,HttpServletRequest request){
//        if (!map.containsKey("clubId")){
//            APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
//        }
//        int clubId = MapUtils.getIntValue(map, "clubId");
        int clubId = reqAgreeJoinClub.getClubId();
        int uid = (int) request.getAttribute("uid");
        int larkAppId = reqAgreeJoinClub.getLarkAppId();
        //先判断是否是俱乐部成员
        if(!clubMemberService.isClubMember(uid, clubId)){
            return APIResponse.returnFail(ClubEnum.CLUB_MEMBER_NOT_EXIST);
        }
        //是此俱乐部成员，执行退出操作
        boolean ret = clubMemberService.quitClub(uid, clubId,larkAppId);
        return APIResponse.returnSuccess(ret);
    }


    /**
     *  编辑俱乐部成员职位、标签
     * @param reqClubMemberEdit     俱乐部成员编辑请求对象
     * @return
     */
    @RequestMapping(value = "/edit")
    public APIResponse<Boolean> editClubMember(@RequestBody ReqClubMemberEdit reqClubMemberEdit, HttpServletRequest request){
        int uid = (int) request.getAttribute("uid");
        //TODO: 判断是否有编辑的权限
        boolean isAuthorized = isAuthorize(uid, reqClubMemberEdit.getClubId(), request);
        if (!isAuthorized){
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }
        //参数校验
        int editType =reqClubMemberEdit.getEditType();
        String roleCode = reqClubMemberEdit.getRoleCode();
        String roleName = reqClubMemberEdit.getRoleName();
        String label = reqClubMemberEdit.getLabel();
        if (editType == ClubConstants.ROLE_EDIT
                && (StringUtil.isBlankOrNull(roleCode) || StringUtil.isBlankOrNull(roleName))){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        if ((editType == ClubConstants.TEAM_LABL_EDIT || editType == ClubConstants.MEMBER_LABEL_EDIT)
                && StringUtil.isBlankOrNull(label)){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        //请求编辑
        boolean ret = clubMemberService.updateClubMember(reqClubMemberEdit.getUid(), editType, reqClubMemberEdit.getClubId(),
                roleCode, roleName, label);

        return APIResponse.returnSuccess(ret);
    }

    /**
     *编辑俱乐部成员
     * @version 2.1.1
     */
    @RequestMapping(value = "/editAll")
    public APIResponse editClubMemberAll(@RequestBody ReqClubMemberEditAll reqEdit, HttpServletRequest request){
        Integer uid = getUid(request, true);
        if (reqEdit.getClubId() == null || reqEdit.getUid() == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        clubMemberService.editClubMemberAll(uid, reqEdit);
        return APIResponse.returnSuccess();
    }

    /**
     * 根据俱乐部成员昵称搜索俱乐部成员
     */
    @RequestMapping(value = "/search")
    public APIResponse<List<RespClubMember>> searchClubMember(@RequestBody Map<String, String> map){
        if (!map.containsKey("clubId") || StringUtil.isBlankOrNull(map.get("nickName"))){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        boolean showFund = false;
        if (map.containsKey("showFund")){
           showFund = MapUtils.getBoolean(map, "showFund");
        }
        return APIResponse.returnSuccess(clubMemberService.searchClubMember(Integer.valueOf(map.get("clubId")), map.get("nickName"), showFund));
    }

    /**
     * 代表队成员添加
     */
    @RequestMapping(value = "/team/add")
    public APIResponse addClubTeamMember(@RequestBody Map<String, String> map, HttpServletRequest request){
        if (!map.containsKey("uids") || !map.containsKey("clubId")){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        int clubId = Integer.valueOf(map.get("clubId"));
        String uids = map.get("uids");  //用户ID，多个用户id，用英文逗号隔开
        if (StringUtil.isBlankOrNull(uids)){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        String[] uidsSplit = uids.split(",");
        List<Integer> uidList = new ArrayList<>();
        for (String uid : uidsSplit){
            if (StringUtil.isBlankOrNull(uid)){
                continue;
            }
            uidList.add(Integer.valueOf(uid));
        }
        return clubMemberService.addClubTeamMember(clubId, uidList);
    }

    /**
     * 代表队成员裁剪
     */
    @RequestMapping(value = "/team/cut")
    public APIResponse cutClubTeamMember(@RequestBody Map<String, String> map, HttpServletRequest request){
        if (!map.containsKey("uids") || !map.containsKey("clubId")){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        String uids = map.get("uids");  //用户ID，多个用户id，用英文逗号隔开
        int clubId = Integer.valueOf(map.get("clubId"));
        if (StringUtil.isBlankOrNull(uids)){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        String[] uidsSplit = uids.split(",");
        List<Integer> uidList = new ArrayList<>();
        for (String uid : uidsSplit){
            if (StringUtil.isBlankOrNull(uid)){
                continue;
            }
            uidList.add(Integer.valueOf(uid));
        }
        return APIResponse.returnSuccess(clubMemberService.cutClubTeamMember(clubId, uidList));
    }
}
